package co.yixiang.controller.buyer.security;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import co.yixiang.cache.Cache;
import co.yixiang.common.annotation.AnonymousAccess;
import co.yixiang.common.annotation.Log;
import co.yixiang.common.enums.ResultCode;
import co.yixiang.common.exception.BadRequestException;
import co.yixiang.common.exception.ServiceException;
import co.yixiang.common.utils.RedisUtils;
import co.yixiang.common.utils.ResultUtil;
import co.yixiang.common.utils.SecurityUtils;
import co.yixiang.common.utils.StringUtils;
import co.yixiang.common.vo.ResultMessage;
import co.yixiang.modules.connect.entity.dto.WechatMPLoginParams;
import co.yixiang.modules.connect.service.ConnectService;
import co.yixiang.modules.member.entity.domain.LoginRequest;
import co.yixiang.modules.member.entity.domain.YxUser;
import co.yixiang.modules.member.entity.domain.YxUserRecharge;
import co.yixiang.modules.member.service.YxUserService;
import co.yixiang.modules.order.order.service.YxStoreCartService;
import co.yixiang.modules.security.config.SecurityProperties;
import co.yixiang.modules.security.entity.domain.Token;
import co.yixiang.modules.security.entity.vo.AuthUser;
import co.yixiang.modules.security.entity.vo.JwtUser;
import co.yixiang.modules.security.security.TokenUtil;
import co.yixiang.modules.security.service.OnlineUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/auth")
@Api(tags = "会员：会员授权接口")
public class AuthBuyerController {
    @Value("${loginCode.expiration}")
    private Long expiration;
    //@Value("${wechat.appid}")
    private String appid;
    //@Value("${wechat.secret}")
    private String secret;
    @Autowired
    private SecurityProperties properties;
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private YxUserService yxUserService;
    @Autowired
    private ConnectService connectService;
    @Autowired
    private Cache cache;
    private final RestTemplate restTemplate = new RestTemplate();
    private final static String URL = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code";

//    @PostMapping("/login")
//    public ResultMessage<String> login(@RequestBody LoginRequest loginRequest) {
//        // 登录
//        // 查询验证码
//        String code = (String) cache.get(loginRequest.getPhone());
//        // 清除验证码
//        cache.remove(loginRequest.getPhone());
//        if (StringUtils.isBlank(code)) {
//            throw new BadRequestException("验证码不存在或已过期");
//        }
//        if (StringUtils.isBlank(loginRequest.getCode()) || !loginRequest.getCode().equalsIgnoreCase(code)) {
//            throw new BadRequestException("验证码错误");
//        }
//        // 用户信息获取，绑定到security
//        // 返回token
////        Map<String, String> params = new HashMap<>(3);
////        params.put("appid", appid);
////        params.put("secret", secret);
////        params.put("js_code", loginRequest.getCode());
//        // restTemplate.getForObject(URL, String.class, params);
//        return ResultUtil.success();
//    }

    @GetMapping("/auto-login")
    @ApiOperation(value = "小程序自动登录")
    public ResultMessage<Token> autoLogin(WechatMPLoginParams params) {
        final Token token = this.connectService.miniProgramAutoLogin(params);
        return ResultUtil.data(token);
    }



//    @Log("用户登录")
//    @ApiOperation("登录授权")
//    @AnonymousAccess
//    @PostMapping(value = "/login")
//    public ResultMessage<Map<String, Object>> login(@Validated @RequestBody AuthUser authUser, HttpServletRequest request) {
//        // 拿到微信的code
//        // 通过微信的code获取到用户信息
//        // 判断用户手机号是否已经注册, 未注册返回错误信息，进行手机号的绑定
//        // 如果已经注册，更新用户信息到数据库
//        // 用户登录初始化购物车
//        // 生成token,用于用户以后的访问
//        cartService.initCart();
//        return ResultUtil.success();
//    }

    @AnonymousAccess
    @ApiOperation("获取验证码")
    @GetMapping(value = "/code")
    public ResultMessage<String> getCode(@RequestBody @NotBlank(message = "手机号不能为空") String phone) {
//        if (ObjectUtil.isEmpty()) {
//            return ResultUtil.error(ResultCode.USER_PHONE_NOT_EXIST);
//        }
        final String key = phone + ":codeCount";
        final String count = cache.getString(key);
        // 调用次数过多
        if (2 > Integer.parseInt(count)) {
            return ResultUtil.error(ResultCode.LIMIT_ERROR);
        }
        // 验证码
        final String code = RandomUtil.randomNumbers(6);
        // TODO: 发送短信验证

        cache.put(key, Integer.parseInt(count) + 1, expiration, TimeUnit.MINUTES);
        cache.put(phone, code, expiration, TimeUnit.MINUTES);
        return ResultUtil.success();
    }
    @ApiOperation("获取用户信息")
    @GetMapping(value = "/info")
    public ResponseEntity<Object> getUserInfo() {
        final AuthUser authUser = SecurityUtils.getAuthUser();
        return ResponseEntity.ok(authUser);
    }

    @ApiOperation("退出登录")
    @AnonymousAccess
    @DeleteMapping(value = "/logout")
    public ResponseEntity<Object> logout(HttpServletRequest request) {
        // onlineUserService.logout(tokenUtil.getToken(request));
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
